package com.zuoban.storage.service.impl;

import com.zuoban.storage.properties.StorageProperties;
import com.zuoban.storage.service.StorageService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.rmi.ServerException;

/**
 * @BelongsProject: zuoban-boot
 * @BelongsPackage: com.zuoban.storage.service.impl
 * @Author: zxy
 * @CreateTime: 2022-10-10
 * @Description: ...
 */
@RequiredArgsConstructor
public class LocalStorageServiceImpl implements StorageService {

    private final StorageProperties storageProperties;


    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            File file = new File(storageProperties.getLocal().getPath() + File.separator + path);

            // 没有目录，则自动创建目录
            File parent = file.getParentFile();
            if (parent != null && !parent.mkdirs() && !parent.isDirectory()) {
                throw new IOException("目录 '" + parent + "' 创建失败");
            }

            FileCopyUtils.copy(inputStream, Files.newOutputStream(file.toPath()));
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败：", e);
        }

        return storageProperties.getConfig().getDomain() + "/" + storageProperties.getLocal().getUrl() + "/" + path;
    }
}
